<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-tabs type="card">
        <a-tab-pane key="1" tab="网点信息">
          <a-form-model
            layout="inline"
            ref="myForm"
            :model="form"
            :rules="validatorRules"
            :label-col="{ style: { width: '150px' } }"
          >
            <a-row :gutter="24">
              <a-col :sm="24" :md="24" :xl="24">
                <a-form-model-item label="商家区域">
                  <a-row :gutter="5">
                    <a-col :span="5">
                      <a-select
                        placeholder="请选择省"
                        v-model="form.businessProvinceCode"
                        @change="(e, data) => addressChange(e, 'cityOptions', 'businessProvince', data.key)"
                      >
                        <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="5">
                      <a-select
                        placeholder="请选择市"
                        v-model="form.businessCityCode"
                        @change="(e, data) => addressChange(e, 'areaOptions', 'businessCity', data.key)"
                      >
                        <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="5">
                      <a-select
                        placeholder="请选择区"
                        v-model="form.businessAreaCode"
                        @change="(e, data) => addressChange(e, 'streetOptions', 'businessArea', data.key)"
                      >
                        <a-select-option v-for="item in areaOptions" :key="item.name" :value="item.code">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="5">
                      <a-select
                        placeholder="请选择街道"
                        v-model="form.businessStreetCode"
                        @change="(e, data) => addressChange(e, '', 'businessStreet', data.key)"
                      >
                        <a-select-option v-for="item in streetOptions" :key="item.name" :value="item.code">
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="4">
                      <a-select placeholder="请选择商家" v-model="form.businessId" @change="agentChange">
                        <a-select-option
                          v-for="item in agentOptions"
                          :key="`${item.name}--${item.phone}`"
                          :value="item.code"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="网点名称" prop="networkName">
                  <a-input placeholder="请输入" v-model="form.networkName" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="服务时间" prop="serviceTime">
                  <a-input-number
                    class="per100"
                    v-model="form.serviceTime"
                    placeholder="请输入服务时间"
                  ></a-input-number>
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="维护人员" prop="maintenanceStaff">
                  <a-input placeholder="请输入" v-model="form.maintenanceStaff" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="维护电话" prop="maintenanceTelephone">
                  <a-input placeholder="请输入" v-model="form.maintenanceTelephone" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="区域" prop="networkNameCollect">
                  <a-cascader
                    v-model="form.networkNameCollect"
                    :options="networkOptions"
                    :load-data="loadNetwork"
                    placeholder="请选择"
                    @change="onChange"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="详细地址" prop="detailAddress">
                  <a-input placeholder="请输入" v-model="form.detailAddress" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="定位地址" prop="locationAddress">
                  <a-input placeholder="请输入" v-model="form.locationAddress" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="经度">
                  <a-input placeholder="请输入" v-model="form.longitude" @change="setLayer()" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="12">
                <a-form-model-item label="纬度">
                  <a-input placeholder="请输入" v-model="form.latitude" @change="setLayer()" />
                </a-form-model-item>
              </a-col>
              <a-col :sm="24" :md="24" :xl="24">
                <a-form-model-item label=" " :colon="false">
                  <a-button type="primary" @click="onSubmit">提交</a-button>
                  <a-button class="ml10" @click="closeCurrent()">返回</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>

          <div id="map" :style="{ width: '100%', height: '500px' }"></div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="网点封面">
          <a-upload-dragger
            name="file"
            :action="uploadUrl"
            :headers="headers"
            list-type="picture"
            @change="handleChange"
            ref="uploadFile"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">点击或拖拽上传</p>
          </a-upload-dragger>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-card>
</template>

<script>
import store from '@/store/'
import TMap from '@/utils/TMap/index'
import Api from '@/api/NetworkManage/NetworkList'
import CommonApi from '@/api/Common/index'
import { httpAction, getAction, putAction } from '@/api/manage'

export default {
  name: 'NetworkUpdate',
  inject: ['closeCurrent'],
  data() {
    return {
      form: {
        id: 0,
        provinceCode: undefined, // 省
        cityCode: undefined, // 市
        areaCode: undefined, // 区
        streetCode: undefined, // 镇
        businessId: undefined, // 商家id
        businessProvinceCode: undefined, // 商家省
        businessCityCode: undefined, // 商家市
        businessAreaCode: undefined, // 商家区
        businessStreetCode: undefined, // 商家镇
        networkName: '', // 网点名称,
        serviceTime: '', // 服务时间
        maintenanceStaff: '', // 维护人员
        maintenanceTelephone: '', // 维护电话
        detailAddress: '', // 详细地址
        locationAddress: '', // 定位地址
        longitude: '', // 经度
        latitude: '', // 纬度,
        networkNameCollect: [],
      },
      loading: false,
      provinceOptions: [],
      cityOptions: [],
      areaOptions: [],
      streetOptions: [],
      agentOptions: [],
      markerLayer: null, // 地图标志
      uploadUrl: `${window._CONFIG['domianURL']}/sys/upload/upload2`,
      headers: {},
      imgUrl: '',
      networkOptions: [],
      fieldNames: {
        label: 'name',
        value: 'code',
        children: 'children',
      },
      validatorRules: {
        networkName: [{ required: true, message: '网点名称不能为空', trigger: 'change' }],
        serviceTime: [{ required: true, message: '服务时间不能为空', trigger: 'change' }],
        maintenanceStaff: [{ required: true, message: '维护人员不能为空', trigger: 'change' }],
        maintenanceTelephone: [{ required: true, message: '维护电话不能为空', trigger: 'change' }],
        networkNameCollect: [{ required: true, message: '区域不能为空', trigger: 'change' }],
        detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'change' }],
        locationAddress: [{ required: true, message: '定位地址不能为空', trigger: 'change' }],
      },
    }
  },
  async mounted() {
    // 获取地址
    this.getAddress('provinceOptions')
    this.headers = {
      'X-Access-Token': store.getters.token,
    }
    // 获取网点下拉
    await this.getAddress('networkOptions', {}, true)
    if (this.$route.params.id !== 'add') {
      this.getDetails()
    } else {
      this.initMap()
    }
  },
  methods: {
    // 获取详情
    getDetails() {
      getAction(Api.queryId, { id: this.$route.params.id })
        .then(async (res) => {
          if (res.code === 200) {
            this.form = res.result
            this.initMap()
            if (this.form.businessProvinceCode) {
              this.getAddress('cityOptions', { provinceCode: this.form.businessProvinceCode })
              if (!this.form.businessCityCode) {
                // 获取商家下拉列表
                this.agentList('agentOptions', { areaCode: this.form.businessAreaCode })
              }
            }
            if (this.form.businessCityCode) {
              this.getAddress('areaOptions', { cityCode: this.form.businessCityCode })
              if (!this.form.businessAreaCode) {
                // 获取商家下拉列表
                this.agentList('agentOptions', { areaCode: this.form.businessAreaCode })
              }
            }
            if (this.form.businessAreaCode) {
              this.getAddress('streetOptions', { areaCode: this.form.businessAreaCode })
              if (!this.form.businessStreetCode) {
                // 获取商家下拉列表
                this.agentList('agentOptions', { areaCode: this.form.businessAreaCode })
              }
            }
            if (this.form.businessStreetCode) {
              this.getAddress('', { streetCode: this.form.businessStreetCode })
              // 获取商家下拉列表
              this.agentList('agentOptions', { streetCode: this.form.businessStreetCode })
            }

            // 网点区域
            if (this.form.provinceCode) {
              this.form.networkNameCollect = [
                this.form.provinceCode,
                this.form.cityCode,
                this.form.areaCode,
                this.form.streetCode,
              ]
              const dataProvince = this.networkOptions.filter((item) => {
                return item.value == this.form.provinceCode
              })
              if (dataProvince.length) {
                await this.loadNetwork(dataProvince)
                const dataCity = dataProvince[0].children.filter((item) => {
                  return item.value == this.form.cityCode
                })
                if (dataCity.length) {
                  await this.loadNetwork(dataCity)
                  const dataArea = dataCity[0].children.filter((item) => {
                    return item.value == this.form.areaCode
                  })
                  this.loadNetwork(dataArea)
                }
              }
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 初始化地图
    initMap() {
      TMap.init().then((TMap) => {
        this.TXMap = TMap
        this.tMap = new TMap.Map('map', {
          center: new TMap.LatLng(39.98412, 116.307484), //设置地图中心点坐标
          zoom: 15, //设置地图缩放级别
          viewMode: '2D',
        })

        // 修改地图中心点
        if (this.form.latitude && this.form.longitude) {
          const position = new TMap.LatLng(this.form.latitude, this.form.longitude)
          this.tMap.setCenter(position)
          this.setLayer()
        } else {
          const ipLocation = new TMap.service.IPLocation()
          ipLocation.locate().then((res) => {
            // 未给定ip地址则默认使用请求端的ip
            const { result } = res
            const position = new TMap.LatLng(result.location.lat, result.location.lng)
            this.tMap.setCenter(position)
            this.setLayer(result.location)
          })
        }

        // 地图点击事件
        this.tMap.on('click', (evt) => {
          const lng = evt.latLng.getLng().toFixed(6)
          const lat = evt.latLng.getLat().toFixed(6)
          this.form.longitude = lng // 经度
          this.form.latitude = lat // 纬度

          this.setLayer(evt.latLng)
        })
      })
    },
    // 设置标志点
    setLayer(position) {
      if (!position) {
        if (this.form.latitude && this.form.longitude) {
          position = new this.TXMap.LatLng(this.form.latitude, this.form.longitude)
          this.tMap.setCenter(position)
        } else {
          this.markerLayer.setMap(null)
          this.markerLayer = null
        }
      }
      if (this.markerLayer) {
        this.markerLayer.setMap(null)
        this.markerLayer = null
      }
      this.markerLayer = new this.TXMap.MultiMarker({
        id: 'marker-layer',
        map: this.tMap,
      })
      // 增加标志
      this.markerLayer.add({
        position,
      })
    },

    // 获取地址
    async getAddress(name, data, bool) {
      await getAction(CommonApi.addressList, data).then((res) => {
        if (bool) {
          this.networkOptions = res.result.map((item) => {
            const newItem = {
              label: item.name,
              value: item.code,
              isLeaf: false,
            }
            return newItem
          })
        } else {
          this[name] = res.result
        }
      })
    },
    // 地址改变
    addressChange(e, name, key, cn) {
      const newKey = key.toLowerCase().replace('business', '')
      this.form[`${newKey}Cn`] = cn
      let obj = {}
      // 改变重置后面市区镇
      if (newKey === 'province') {
        obj = {
          businessCityCode: undefined,
          businessCityCn: undefined,
          businessAreaCode: undefined,
          businessAreaCn: undefined,
          businessStreetCode: undefined,
          businessStreetCn: undefined,
          businessId: undefined,
        }
        this.businessCityOptions = []
        this.businessAreaOptions = []
        this.businessStreetOptions = []
      } else if (newKey === 'city') {
        obj = {
          businessAreaCode: undefined,
          businessAreaCn: undefined,
          businessStreetCode: undefined,
          businessStreetCn: undefined,
          businessId: undefined,
        }
        this.businessAreaOptions = []
        this.businessStreetOptions = []
      } else if (newKey === 'area') {
        obj = {
          businessStreetCode: undefined,
          businessStreetCn: undefined,
          businessId: undefined,
        }
        this.businessStreetOptions = []
      } else if (newKey === 'street') {
        obj = {
          businessId: undefined,
        }
      }
      this.form = { ...this.form, ...obj }
      if (name && e) {
        this.getAddress(name, { [`${newKey}Code`]: e })
      }
      // 重新请求商家
      this.agentList('agentOptions', { [`${newKey}Code`]: e })
    },

    // 获取商家网点设备下拉列表
    agentList(name, data) {
      getAction(CommonApi.agentList, data).then((res) => {
        this[name] = res.result
      })
    },

    // 上传改变
    handleChange(info) {
      const status = info.file.status
      if (status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (status === 'done') {
        if (info.fileList && info.fileList.length === 2) {
          info.fileList.splice(0, 1)
        }
        this.form.networkCover = info.file.response.message
        putAction(Api.uploadCover, { id: this.form.id, networkCover: info.file.response.message }).then((res) => {
          if (res.code === 200) {
            this.$message.success(`上传封面成功`)
          } else {
            this.$message.error(`上传封面失败`)
          }
        })
      } else if (status === 'error') {
        this.$message.error(`上传封面失败`)
      }
    },

    agentChange(e, a, b) {
      this.form.maintenanceStaff = a.key.split('--')[1]
    },
    // 提交
    onSubmit() {
      let url = Api.add
      let method = 'post'
      if (this.form.id > 0) {
        url = Api.edit
        method = 'put'
      }
      this.$refs.myForm.validate((valid) => {
        if (valid) {
          this.loading = true
          httpAction(url, this.form, method)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success(res.message)
                this.closeCurrent()
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    async loadNetwork(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true
      let data = {}
      let isLeaf = false
      // load options lazily
      if (targetOption.value.length === 2) {
        // 请求市
        data = { provinceCode: targetOption.value }
      } else if (targetOption.value.length === 4) {
        // 请求区
        data = { cityCode: targetOption.value }
      } else if (targetOption.value.length === 6) {
        // 请求街道
        isLeaf = true
        data = { areaCode: targetOption.value }
      }
      await getAction(CommonApi.addressList, data).then((res) => {
        targetOption.children = res.result.map((item) => {
          const newItem = {
            label: item.name,
            value: item.code,
            isLeaf,
          }
          return newItem
        })
      })
      targetOption.loading = false
      this.networkOptions = [...this.networkOptions]
    },

    onChange(e, item) {
      let obj = {}
      if (e.length) {
        obj = {
          provinceCode: item[0].value,
          provinceCn: item[0].label,
          cityCode: item[1].value,
          cityCn: item[1].label,
          areaCode: item[2].value,
          areaCn: item[2].label,
          streetCode: item[3].value,
          streetCn: item[3].label,
        }
      } else {
        obj = {
          cityCode: '',
          cityCn: '',
          areaCode: '',
          areaCn: '',
          streetCode: '',
          streetCn: '',
        }
      }
      this.form = { ...this.form, ...obj }
    },
  },
}
</script>

<style scoped></style>

